package com.itheima.d4_algorithm;

/**
 * 目标：掌握二分查找算法。
 *
 * binarySearch
 */
public class Test3 {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9};
        System.out.println(test(arr, 2));
    }
    public static int  test(int[] arr ,int num){
        //二分查找
        //1.定义左坐标和右坐标
        int left  = 0;
        int right = arr.length-1;
        //定循环，查找要找的数据
        while (left<=right){
            //定义中间数据坐标
            int mid = (left+right)/2;
            //判断中间坐标对于右边是大还是小
            if(arr[mid]>num){
                //就说明mid在num的右边
                right=mid-1;
            } else if (arr[mid]<num) {
                left=mid+1;
            }else {
                //中间数，和查找的数据相同
                return mid;
            }
        }
        return -1;
    }
}
